//
//  BanBu_EmoKeyboard.m
// Halfarea
//
//  Created by Wang Xj on 14-4-9.
//
//

#import "BanBu_EmoKeyboard.h"
#import "BanBu_EmoManger.h"
#import "BanBu_SmileViewAPI.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "SCGIFImageView.h"

//tag值：10000到10100，这是下载表情的按钮
//tag值：10101到10103，分别是表情、收藏、字符三个按钮的tag值
//tag值：100001到100100，这是收藏表情中所有图片的tag值
//tag值：100101到100199，这是下载表情中显示到界面上的图片的tag值
#define DeleteTag 999

@implementation BanBu_EmoKeyboard

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization

    }
    return self;
}

-(void)viewDidLoad
{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshCollectedEmo) name:KRefreshCollectedEmo object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshDownloadedEmo) name:KRefreshDownloadedEmo object:nil];
    
    [_sendButton setTintColor:[UIColor whiteColor]];
    _sendButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    _sendButton.hidden = YES;
    
    self.inputedStr = [NSMutableArray arrayWithCapacity:5];
    
    UIImageView *bkView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];//-40
    bkView.image = [UIImage imageNamed:@"chatbg.png"];
    [self.view insertSubview:bkView atIndex:0];
    [bkView release];
    
    [self initWithKeyboard];
    
    _defaultEmoScrollView.hidden = NO;
    _pageControl.numberOfPages = 2;
    _pageControl.currentPage = 0;
    _selectedTag = 10101;
}

- (void)viewDidUnload
{
    [self setCollectionScrollView:nil];
    [self setSendButton:nil];
    [super viewDidUnload];
}

-(void)viewWillAppear:(BOOL)animated
{
//    [self.view bringSubviewToFront:_newView];
//    [self.view bringSubviewToFront:_emoTypeScrollView];
}

- (void)dealloc
{
    [_emoInfoDic release],_emoInfoDic = nil;
    [_collectedArr release],_collectedArr = nil;
    [_inputedStr release],_inputedStr = nil;
    [_keyboardScrollView release];
    [_emoTypeScrollView release];
    [_pageControl release];
    [_defaultEmoScrollView release];
    [_characterScrollView release];
    [_EmoScrollView release];
    [_backgroundImageView release];
    [_showBigView release];
    [_BigView release];
    [_CollectionScrollView release];
    [_sendButton release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KRefreshCollectedEmo object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KRefreshDownloadedEmo object:nil];
    [super dealloc];
}

#pragma mark - 初始化键盘

//初始化键盘内容
-(void)initWithKeyboard
{
    UIButton * button = (UIButton *)[_emoTypeScrollView viewWithTag:10101];
    UIImageView * imageView = [[UIImageView alloc]init];
    imageView.frame = CGRectMake(15, 5, 30, 30);
    imageView.image = [UIImage imageNamed:@"btn_emo_emo.png"];
    [button addSubview:imageView];
    [imageView release];
    
    button = (UIButton *)[_emoTypeScrollView viewWithTag:10102];
    UIImageView * imageView1 = [[UIImageView alloc]init];
    imageView1.frame = CGRectMake(15, 5, 30, 30);
    imageView1.image = [UIImage imageNamed:@"btn_emo_collect.png"];
    [button addSubview:imageView1];
    [imageView1 release];
    
    
    button = (UIButton *)[_emoTypeScrollView viewWithTag:10103];
    UIImageView * imageView2 = [[UIImageView alloc]init];
    imageView2.frame = CGRectMake(15, 5, 30, 30);
    imageView2.image = [UIImage imageNamed:@"btn_emo_charactor.png"];
    [button addSubview:imageView2];
    [imageView2 release];
    
    
    //默认表情
    [self initWithDefaultEmo];
    
    //字符
    [self initWithCharater];
    
    //收藏
    NSMutableDictionary * collectedEmoDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectEmoInfoPath]];
    
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:collectedEmoDic.allValues];
    
    [self initWithCustEmo:array];
    
    [array release];
    [collectedEmoDic release];
    
    [_keyboardScrollView addSubview:_CollectionScrollView];
    
    //下载的表情
    [self initWithEmoType];
    
    _emoTypeScrollView.backgroundColor = [UIColor clearColor];
    
//    [self.view bringSubviewToFront:_newView];
//    [self.view bringSubviewToFront:_emoTypeScrollView];
}

#pragma mark - 默认的表情
//默认表情
-(void)initWithDefaultEmo
{
    NSInteger page = 0;
    _pageControl.numberOfPages = 2;
    _pageControl.currentPage = 0;
    _defaultEmoScrollView.contentSize= CGSizeMake(320*2, 176);
    
    NSArray  *smileArr = [NSArray arrayWithObjects:@"打怪兽",@"嘟嘟嘴",@"多变",@"饿了",@"高兴",@"歌王",@"好烦啊",@"加油",@"惊讶",@"可爱",@"可怜",@"麦霸",@"怒火",@"饶命",@"撒娇",@"睡觉",@"痛苦",@"羞羞脸",@"阴谋",@"眨眼",@"发大财",@"喷饭",@"炸飞了",@"凄凉",@"T台秀",@"读书",@"扭屁股",@"舞蹈",@"得意",@"运动",@"救命",@"滚远点",@"江南舞",@"走你", nil];
    
    for(int i=0; i<[smileArr count]; i++)
    {
        NSString *imageName = [NSString stringWithFormat:@"%@",[smileArr objectAtIndex:i]];
        NSString *path=[[NSBundle mainBundle]pathForResource:imageName ofType:@"gif"];
        SCGIFImageView *gif=[[SCGIFImageView alloc]initWithGIFFile:path];
        gif.userInteractionEnabled=YES;
        gif.frame=CGRectMake(320*page+10+52*(i%6), 50*(i/6-3*page), 35, 35);
        gif.backgroundColor=[UIColor blackColor];
        gif.tag=i;
        
        //加一个手势 让他触发方法
        UITapGestureRecognizer *tapGester=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(btnPress:)];
        [gif addGestureRecognizer:tapGester];
        [tapGester release];
        [_defaultEmoScrollView addSubview:gif];
        [gif release];
        
        if(i>16 && !page)
            page = 1;
        if(i>34)
        {
            page = 2;
        }
    }
    
    
    [_keyboardScrollView addSubview:_defaultEmoScrollView];
    
//    [self.view bringSubviewToFront:_newView];
//    [self.view bringSubviewToFront:_emoTypeScrollView];
}


#pragma mark - 字符
//字符
-(void)initWithCharater
{
    NSInteger page = 0;
    _pageControl.numberOfPages = 3;
    _pageControl.currentPage = 0;
    
    _characterScrollView.delegate = self;
    _characterScrollView.backgroundColor = [UIColor clearColor];
    _characterScrollView.showsHorizontalScrollIndicator = NO;
    _characterScrollView.pagingEnabled = YES;
    [_characterScrollView setContentSize:CGSizeMake(320*4, 175)];

    NSArray *titles = [NSArray arrayWithObjects:@"T_T",@"⊙ ⊙",@"~~>_<~~",@"^_~",@"*o*",@":p",@"@_@",@"<@_@>",@"o_o",@"^o^",@"O_O",@"-_-",@"^_^",@"＿.,＿",@"^v^",@"^^v",@"(^-^)",@"=_=^",@"=^_^=",@"*^_^*",@"=_=",@"+_+",@"?_?",@"$_$",@"~_~",@"T^T",@">o<",@"e_e",@"－_－#",@"－_－b",@"－_－^",@">_<",@"－O－",@"O(∩_∩)O~",@"(*^__^*)",@"\(^o^)/~",@"( ⊙o⊙ )",@"╭(╯^╰)╮",@"（¯『¯）",@"o(≥v≤)o~~",@"~(@^_^@)~",@"(^ω^)",@"(*^◎^*)",@"(+﹏+)~",@"o(╯□╰)o",@"╭∩╮",@"-_-|||",@"( ^_^ )/~~",@"(ˉ(∞)ˉ)" ,nil];
    int j = 0;
    for(int i=0; i<53; i++)
    {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(320*page+80*(i%4),34*(i/4-4*page), 79,33);
        
        if ((i+1)%16 == 0)
        {
            [button setImage:[UIImage imageNamed:@"btn_em_delete.png"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = DeleteTag;
        }
        else if(i != 52)
        {
            [button setBackgroundImage:[UIImage imageNamed:@"button_emotion.png"] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
            [button setTitle:[titles objectAtIndex:j] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = j;
            j++;
        }
        else
        {
            button.frame = CGRectMake(320*page+80*3,34*3, 79,33);
            [button setImage:[UIImage imageNamed:@"btn_em_delete.png"] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(btnPressed:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = DeleteTag;
        }
        
        [_characterScrollView addSubview:button];
        if(i>14 && !page)
            page = 1;
        if(i>30 && i<46)
        {
            page = 2;
        }
        else if(i>46)
        {
            page = 3;
        }
    }
    
    [_keyboardScrollView addSubview:_characterScrollView];
    
//    [self.view bringSubviewToFront:_newView];
//    [self.view bringSubviewToFront:_emoTypeScrollView];
}

#pragma mark - 收藏的表情
//收藏的表情
-(void)initWithCustEmo:(NSArray *)emoInfoArr
{
    self.collectedArr = [NSMutableArray arrayWithArray:emoInfoArr];
    
    [_collectedArr sortUsingFunction:compare context:NULL];
    
    NSInteger imagCount = _collectedArr.count;
    
    CGRect frame = _CollectionScrollView.frame;

    [_CollectionScrollView removeFromSuperview];
    
    self.CollectionScrollView = [[[UIScrollView alloc]initWithFrame:frame] autorelease];
    
    _CollectionScrollView.delegate = self;
    _CollectionScrollView.backgroundColor = [UIColor clearColor];
    _CollectionScrollView.showsHorizontalScrollIndicator = NO;
    _CollectionScrollView.pagingEnabled = YES;
    _CollectionScrollView.hidden = YES;
    
    if (imagCount==0)//没有收藏的表情
    {
        _CollectionScrollView.contentSize = CGSizeMake(320, 175);
        imagCount  = 1;
    }
    else
    {
        _CollectionScrollView.contentSize = CGSizeMake(320*ceilf((imagCount+1)/8.0), 175);
    }
    
    _CollectionScrollView.pagingEnabled = YES;
    _pageControl.numberOfPages = ceilf(imagCount/8.0);
    
    NSInteger page = 0;
    
    for (int i = 0;i<_collectedArr.count+1;i++)
    {
        if (i == 0)
        {
            UIButton * setButton = [UIButton buttonWithType:UIButtonTypeCustom];
            setButton.frame  = CGRectMake(15, 15, 55, 55);
            [setButton setImage:[UIImage imageNamed:@"btn_emo_collection.png"] forState:UIControlStateNormal];
            [setButton addTarget:self action:@selector(goinToCollection:) forControlEvents:UIControlEventTouchUpInside];
            
            [_CollectionScrollView addSubview:setButton];
            continue;
        }
        
        NSDictionary * emoDic = [_collectedArr objectAtIndex:i-1];
        
        UIButton * Button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        frame = CGRectMake(320*page+80*(i%4) + 15, 15+80*((i%8)/4), 55, 55);;
        
        Button.frame = frame;
        Button.tag = 100001+i;
        
        UIImageView * imageView = [[UIImageView alloc]init];
        //查缓存，没有缓存时下载并显示
        NSString * imageName = [emoDic valueForKeyPath:KeyName];
        NSString * imageUrl = [emoDic valueForKey:KeyPath];
        
        [imageView setImageWithUrlString:imageUrl withFolderName:CollectionFolder withImageName:imageName];
        
        [Button setImage:imageView.image forState:UIControlStateNormal];
        [Button addTarget:self action:@selector(btnCollectedPressed:) forControlEvents:UIControlEventTouchUpInside];

        [_CollectionScrollView addSubview:Button];
        if ((i+1)%8==0)
        {
            page += 1;
        }
        [imageView release];
    }
    
//    [self.view bringSubviewToFront:_newView];
//    [self.view bringSubviewToFront:_emoTypeScrollView];
}


#pragma mark - 表情商店表情
//下载的表情
-(void)initWithEmoType
{
    //获取下载的表情的种类信息
    NSDictionary * downloadEmoDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadInfoPath];
    
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:downloadEmoDic.allValues];
    
    [array sortUsingFunction:compare context:NULL];
    
    self.emoArr = array;
    
    [_emoTypeScrollView setContentSize:CGSizeMake(240+60*self.emoArr.count+60, 40)];
    NSLog(@"%f",_emoTypeScrollView.frame.size.width);
    
//    _emoTypeScrollView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"btn_emoType_bg.png"]];
    
    //添加下载的表情
    for (int i = 0 ;i < self.emoArr.count; i++)
    {
        NSDictionary * oneEmoInfo = [self.emoArr objectAtIndex:i];
        
        //添加button
        UIButton * button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(240 + i*60, 0, 60, 40);

        NSString * imageName = @"icon.png";
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[oneEmoInfo valueForKey:KeyPath],imageName];
        
        UIImageView * imageView = [[UIImageView alloc]init];
        imageView.frame = CGRectMake(15, 5, 30, 30);
        
        [imageView setImageWithUrlString:imageUrl withFolderName:[AppComManager remove_:[oneEmoInfo valueForKeyPath:Keyid]] withImageName:imageName];
        
        [button addSubview:imageView];
        
        button.tag = 10000+i;
        [button setBackgroundImage:[UIImage imageNamed:@"btn_emoType_normal.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"btn_emoType_Pressed.png"] forState:UIControlStateHighlighted];
        
        [button addTarget:self action:@selector(changeEmoType:) forControlEvents:UIControlEventTouchUpInside];
        
        [_emoTypeScrollView addSubview:button];
        [imageView release];
        
    }
    
    //添加进入表情商店的“加号”按钮
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    
    button.frame = CGRectMake(0, 0, 60, 40);
    button.tag = 10000 + self.emoArr.count;
    [button setBackgroundImage:[UIImage imageNamed:@"btn_emoType_add.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(goinToEmoStore:) forControlEvents:UIControlEventTouchUpInside];
    _addstoreBu = button;
    //是否添加更新信息
    NSDictionary * versionDic = [UserDefaults valueForKey:@"versionBoolInfo"];
    BOOL versionBl = [[versionDic valueForKey:@"facestore_ver"] boolValue];
    
    if (versionBl)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:[NSString stringWithFormat:@"%d",versionBl] activityAnimated:NO duration:1.3f];
    }
    
    BOOL bl = [[UserDefaults valueForKey:@"hiddenNew"] boolValue];
    
    if (!bl)
    {//添加new标志
        _newView = [[UIImageView alloc]initWithFrame:CGRectMake(40, 0, 20, 20)];
        _newView.image = [UIImage imageNamed:@"btn_emo_new.png"];
        _newView.backgroundColor = [UIColor clearColor];
        _newView.tag = 110000;
        
        [button addSubview:_newView];
    }
    
    [_emoTypeScrollView addSubview:button];
}

#pragma mark -刷新键盘
//刷新收藏的表情键盘
-(void)refreshCollectedEmo
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"collectingSucceed", nil) activityAnimated:NO duration:1.2f];
    });

    //收藏
    NSMutableDictionary * collectedEmoDic = [[NSMutableDictionary alloc]initWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithFile:CollectEmoInfoPath]];
    
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:collectedEmoDic.allValues];
    
    //初始化收藏表情
    [self initWithCustEmo:array];
    [_keyboardScrollView addSubview:_CollectionScrollView];
    
    [array release];
    [collectedEmoDic release];
    
    if (_selectedTag == 10102)
    {
        _CollectionScrollView.hidden = NO;
    }
}

-(void)refreshDownloadedEmo
{
    for (int i =10000; i<101000;i++)
    {
        UIButton *button=(UIButton *)[_emoTypeScrollView viewWithTag:i];
        
        if (button)
        {
            [button removeFromSuperview];
        }
        else
        {
            break;
        }
    }
    [self changeToDefaultEmo];
    //添加按钮
    [self initWithEmoType];
    [_addstoreBu setImage:[UIImage imageNamed:@"btn_emoType_add.png"] forState:UIControlStateNormal];
    [_emoTypeScrollView bringSubviewToFront:_addstoreBu];
    
}

-(void)refreshDownloadedEmoType
{
    [self initWithEmoType];
}

#pragma mark - 切换到默认表情
/**
 * @函数名称：changeToDefaultEmo
 * @函数描述：恢复到默认表情，删除表情商店表情使用(该表情已被卸载，但仍在对话框中)
 * @输入参数：nil
 * @输出参数：nil
 * @返回值：恢复到默认表情
 * @author：yinlinlin
 */
- (void)changeToDefaultEmo
{
    _defaultEmoScrollView.hidden = NO;
    _characterScrollView.hidden = YES;
    _CollectionScrollView.hidden = YES;
    _EmoScrollView.hidden = YES;
    _sendButton.hidden = YES;
    [_sendButton setBackgroundImage:[UIImage imageNamed:@"btn_emo_send.png"] forState:UIControlStateNormal];
    [_sendButton setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
    _pageControl.numberOfPages = 2;
    _pageControl.currentPage = 0;
}
#pragma mark - 切换键盘
//切换默认键盘：表情、收藏、符号
- (IBAction)changeDefaultKeyboard:(UIButton *)sender
{
    if (_selectedTag == sender.tag)//点的是同一个表情
    {
        return;
    }
    
    UIButton *button = (UIButton *)[_emoTypeScrollView viewWithTag:_selectedTag];
    [button setBackgroundImage:[UIImage imageNamed:@"btn_emoType_normal.png"] forState:UIControlStateNormal];
    [sender setBackgroundImage:[UIImage imageNamed:@"btn_emoType_Pressed.png"] forState:UIControlStateNormal];
    
    _selectedTag = sender.tag;
    
    int tag = _selectedTag - 10101;
    _emoInfoDic = nil;
    
    if (tag == 0)//表情
    {
        _defaultEmoScrollView.hidden = NO;
        _characterScrollView.hidden = YES;
        _CollectionScrollView.hidden = YES;
        _EmoScrollView.hidden = YES;
        _sendButton.hidden = YES;
        [_sendButton setBackgroundImage:[UIImage imageNamed:@"btn_emo_send.png"] forState:UIControlStateNormal];
        [_sendButton setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
        _pageControl.numberOfPages = 2;
        _pageControl.currentPage = 0;
    }
    else if (tag == 1)//收藏
    {
        _defaultEmoScrollView.hidden = YES;
        _characterScrollView.hidden = YES;
        _CollectionScrollView.hidden = NO;
        _EmoScrollView.hidden = YES;
        _sendButton.hidden = YES;
    }
    else if (tag == 2)//字符
    {
        [_sendButton setBackgroundImage:[UIImage imageNamed:@"btn_emo_send.png"] forState:UIControlStateNormal];
        [_sendButton setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];

        _defaultEmoScrollView.hidden = YES;
        _characterScrollView.hidden = NO;
        _CollectionScrollView.hidden = YES;
        _EmoScrollView.hidden = YES;
        _sendButton.hidden = NO;
        
        _pageControl.numberOfPages = 3;
        _pageControl.currentPage = 0;
    }
}

//切换下载表情键盘
-(void)changeEmoType:(UIButton *)sender
{
    if (_selectedTag == sender.tag)
    {
        return;
    }
    _sendButton.hidden = YES;
    
    UIButton *button = (UIButton *)[_emoTypeScrollView viewWithTag:_selectedTag];
    [button setBackgroundImage:[UIImage imageNamed:@"btn_emoType_normal.png"] forState:UIControlStateNormal];
    [sender setBackgroundImage:[UIImage imageNamed:@"btn_emoType_Pressed.png"] forState:UIControlStateNormal];
    
    _selectedTag = sender.tag;
    int index = sender.tag - 10000;
    
    //选择的表情是
    NSDictionary * selectedEmo = [self.emoArr objectAtIndex:index];
    
    //显示选中的view
    [self setSelectedEmo:selectedEmo];
}

//设置选中表情键盘
-(void)setSelectedEmo:(NSDictionary *)emoDic
{
    self.emoInfoDic = emoDic;
    
    NSInteger count = [[emoDic valueForKey:KeyCount] integerValue];
    NSInteger page = 0;
    _pageControl.frame = CGRectMake(0, 154, 320, 10);
    _pageControl.numberOfPages = ceil(count/8.0);
    _pageControl.currentPage = 0;

    CGRect frame = _EmoScrollView.frame;
    [_EmoScrollView removeFromSuperview];
    _EmoScrollView = nil;
    
    self.EmoScrollView = [[[UIScrollView alloc]initWithFrame:frame] autorelease];
    
    _EmoScrollView.delegate = self;
    _EmoScrollView.backgroundColor = [UIColor clearColor];
    _EmoScrollView.showsHorizontalScrollIndicator = NO;
    _EmoScrollView.pagingEnabled = YES;
    [_EmoScrollView setContentSize:CGSizeMake(320*_pageControl.numberOfPages, 175)];
    
    for(int i=0; i < count; i++)
    {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(320*page+80*(i%4) + 15, 15+80*((i%8)/4), 55, 55);
        
        UIImageView * imageView = [[UIImageView alloc]init];
        NSString * imageName = [NSString stringWithFormat:@"%d.gif",i+1];
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[emoDic valueForKey:KeyPath],imageName];
        
        [imageView setImageWithUrlString:imageUrl withFolderName:[AppComManager remove_:[emoDic valueForKeyPath:Keyid]] withImageName:imageName];
        button.tag = 100101 + i;
        
        [button setImage:imageView.image forState:UIControlStateNormal];
        [button addTarget:self action:@selector(btnEmoPress:) forControlEvents:UIControlEventTouchUpInside];
        
        [_EmoScrollView addSubview:button];
        if ((i+1)%8==0)
        {
            page += 1;
        }
        
        [imageView release];
    }

    [_keyboardScrollView addSubview:_EmoScrollView];
    
    _defaultEmoScrollView.hidden = YES;
    _characterScrollView.hidden = YES;
    _CollectionScrollView.hidden = YES;
    _EmoScrollView.hidden = NO;
    _sendButton.hidden = YES;
}

#pragma mark - 发送字符
//发送
- (IBAction)sendEmo:(UIButton *)sender
{
    if (sender.currentTitle.length)//发送
    {
        //发送消息时使用的方法
        if (self.selectedTag == 10103)
        {
            if ([self.delegate respondsToSelector:@selector(sendCharactor)])
            {
                [self.delegate sendCharactor];
            }
        }
    }
    else//删除
    {
        if([_delegate respondsToSelector:@selector(banBu_SmileView:didInputSmile:isDelete:type:)])
            [_delegate banBu_SmileView:self didInputSmile:nil isDelete:YES type:0];
    }
}

#pragma mark - 表情键盘的代理处理
//发送：默认表情
-(void)btnPress:(UITapGestureRecognizer *)tap
{
    NSString *inputStr=nil;
    NSArray  *smileArr = [NSArray arrayWithObjects:@"打怪兽",@"嘟嘟嘴",@"多变",@"饿了",@"高兴",@"歌王",@"好烦啊",@"加油",@"惊讶",@"可爱",@"可怜",@"麦霸",@"怒火",@"饶命",@"撒娇",@"睡觉",@"痛苦",@"羞羞脸",@"阴谋",@"眨眼",@"发大财",@"喷饭",@"炸飞了",@"凄凉",@"T台秀",@"读书",@"扭屁股",@"舞蹈",@"得意",@"运动",@"救命",@"滚远点",@"江南舞",@"走你", nil];
    inputStr=[smileArr objectAtIndex:tap.view.tag];
    
    if([_delegate respondsToSelector:@selector(banBu_SmileView:didInputSmile:isDelete:type:)])
        [_delegate banBu_SmileView:self didInputSmile:inputStr isDelete:NO type:1];
}

#pragma mark - 字符删除按钮和字符按钮点击事件
//发送：字符消息
- (void)btnPressed:(UIButton *)button
{
    if(button.tag == DeleteTag)
    {
        if([_delegate respondsToSelector:@selector(banBu_SmileView:didInputSmile:isDelete:type:)])
            [_delegate banBu_SmileView:self didInputSmile:nil isDelete:YES type:0];
    }
    else
    {
        NSString *inputStr = nil;
        inputStr = button.titleLabel.text;
        [self.inputedStr addObject:inputStr];
        if([_delegate respondsToSelector:@selector(banBu_SmileView:didInputSmile:isDelete:type:)])
            [_delegate banBu_SmileView:self didInputSmile:inputStr isDelete:NO type:0];
        
    }
}


#pragma mark - 发送收藏的表情
//发送：收藏的表情
-(void)btnCollectedPressed:(UIButton *)tap
{
    NSInteger tagIndex = tap.tag - 100002;//收藏的表情的索引index
    NSDictionary * emoDic = [_collectedArr objectAtIndex:tagIndex];
    
    //网络路径
    NSString * imageUrl = [NSString stringWithFormat:@"%@",[emoDic valueForKey:KeyPath]];
    if([_delegate respondsToSelector:@selector(BanBu_EmoViewInputSmile:type:filePathExtension:)])
    {
        [_delegate BanBu_EmoViewInputSmile:imageUrl type:0 filePathExtension:[emoDic valueForKey:KeyExtension]];
    }
}

//发送：下载的表情
-(void)btnEmoPress:(UIButton *)tap
{
    //先找出发送的是那一套表情
    NSInteger tagIndex = tap.tag - 100100;//收藏的表情的索引index
    NSString * imageName = [NSString stringWithFormat:@"%d.gif",tagIndex];
    
    //网络路径
    NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[_emoInfoDic valueForKey:KeyPath],imageName];
    
    if([_delegate respondsToSelector:@selector(BanBu_EmoViewInputSmile:type:filePathExtension:)])
    {
        [_delegate BanBu_EmoViewInputSmile:imageUrl type:1 filePathExtension:@"gif"];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    _pageControl.currentPage = scrollView.contentOffset.x/320;
}

#pragma mark - 预览大图
//长按缩略图时显示大图
-(void)showBigImage:(UILongPressGestureRecognizer *)gesture
{
    //先判断点的是哪个缩略图
    CGPoint locationPoint = [gesture locationInView:_EmoScrollView];
    NSInteger x = (int)locationPoint.x %320;
    NSInteger y = locationPoint.y;
    NSInteger tagIndex = 100001;
    
    if (x < 75)//第一列
    {
        x = 10 +100;//100是大图的宽的一半，x，y是大图的中心点坐标
        tagIndex += _pageControl.currentPage*8;
    }
    else if (x<92+60)//第二列
    {
        x = 22 +100;
        tagIndex += _pageControl.currentPage*8 + 1;
    }
    else if (x< 168+60)//第三列
    {
        x = 98 +100;
        tagIndex += _pageControl.currentPage*8 + 2;
    }
    else//第四列
    {
        x = 110 +100;
        tagIndex += _pageControl.currentPage*8 + 3;
    }
    
    if (y<70)//第一行
    {
        y = 190;
    }
    else//第二行
    {
        y = 280;
        tagIndex += 4;
    }
    
    if (x <= 110)//在左边时
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_left.png"];
    }
    else if (x >= 210)//
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_right.png"];
    }
    else
    {
        _backgroundImageView.image = [UIImage imageNamed:@"emo_showBackground_middle.png"];
    }
    
    if (((int)_showBigView.center.x != x) || ((int)_showBigView.center.y != y))
    {
        //去下载大图
        _showBigView.center = CGPointMake(x, y);
        NSString * imageName = [NSString stringWithFormat:@"%d.gif",tagIndex-100000];
        NSString * imageUrl = [NSString stringWithFormat:@"%@%@",[_emoInfoDic valueForKey:KeyPath],imageName];
        [_BigView setImageWithUrlString:imageUrl withFolderName:[AppComManager remove_:[_emoInfoDic valueForKeyPath:Keyid]] withImageName:imageName];
    }
    
    switch (gesture.state)
    {
        case UIGestureRecognizerStateBegan:
        {
            _showBigView.hidden = NO;
        }
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateCancelled:
        {
            [_BigView setImageWithURL:nil];
            _showBigView.hidden = YES;
            gesture.view.backgroundColor = [UIColor clearColor];
        }
        default:
            break;
    }
}

-(void)goinToEmoStore:(UIButton *)sender
{
    if ([_delegate respondsToSelector:@selector(goinToEmoStore: withNextView:)])
    {
        [UserDefaults setValue:[NSNumber numberWithBool:YES] forKey:@"hiddenNew"];
        [UserDefaults synchronize];
        
        UIImageView * imageView = (UIImageView *)[_emoTypeScrollView viewWithTag:110000];
        imageView.hidden = YES;
        
        [_delegate goinToEmoStore:self withNextView:@"store"];
    }
}

-(void)goinToCollection:(UIButton *)sender
{
    if ([_delegate respondsToSelector:@selector(goinToEmoStore: withNextView:)])
    {
        [_delegate goinToEmoStore:self withNextView:@"collect"];
    }
}


@end
